package sskj.regulatory.domain.interactor

import android.content.SharedPreferences
import com.hikvision.sdk.VMSNetSDK
import com.hikvision.sdk.net.bean.LoginData
import com.hikvision.sdk.net.business.OnVMSNetSDKBusiness
import com.vondear.rxtools.view.RxToast
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.FlowableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import kotlinx.android.synthetic.main.fragment_register_captcha.view.*
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
import sskj.regulatory.App
import sskj.regulatory.data.network.ApiConstants
import sskj.regulatory.data.pref.Preferences
import sskj.regulatory.data.response.session.IndexDataResponse
import sskj.regulatory.data.response.Response
import sskj.regulatory.data.response.eng.EngResponse
import sskj.regulatory.data.response.session.TokenResponse
import sskj.regulatory.di.scope.PerActivity
import sskj.regulatory.domain.entity.user.BingDingEntity
import sskj.regulatory.domain.entity.user.UserEntity
import sskj.regulatory.domain.fetcher.result_listener.RequestType
import sskj.regulatory.domain.repository.UserRepository
import sskj.regulatory.presentation.constans.Constans
import sskj.regulatory.presentation.constans.Constans.JK_ROLE_ID
import sskj.regulatory.presentation.screen.registeCaptcha.RegisterCaptchaFragment
import java.util.ResourceBundle.clearCache
import javax.inject.Inject


@PerActivity
class UserInteractor @Inject constructor(private val userDataRepository: UserRepository) {

    //绑定用户
    fun bingDing(bingDingEntity: BingDingEntity): Flowable<Response> {
        return userDataRepository.bingDing(bingDingEntity)
    }

    //绑定用户
    fun delBingDing(id: String): Flowable<Response> {
        return userDataRepository.delBingDing(id)
    }


    //项目部扫码登录
    fun xmbQrLogin(qrCode: String, username: String, password: String): Flowable<Response> {
        return userDataRepository.xmbQrLogin(qrCode, username, password)
    }

    //项目部扫码登录
    fun xmbDoQrLogin(qrCode: String): Flowable<Response> {
        return userDataRepository.xmbDoQrLogin(qrCode, true)
    }

    //项目部认证
    fun xmbAuth(username: String, password: String): Flowable<EngResponse> {
        return userDataRepository.xmbAuth(username, password)
    }

    //更新TOKEN
    fun refreshToken(): Flowable<TokenResponse> {
        return userDataRepository.refreshToken()
                .doOnNext { userDataRepository.saveToken(it.data?.token) }
    }

    //发送验证码
    fun sendVCode(phone: String, vCode: String, signName: String = "升思科技",
                  templateCode: String = "SMS_128880244", templateParam: String = "", outId: String = "vcode"): Flowable<Response> {
        return userDataRepository.sendVCode(phone, vCode, signName, templateCode, templateParam, outId).doOnNext {
            userDataRepository.saveAlong()
        }
    }

    //判断用户名是否存在
    fun isRegister(username: String): Flowable<Response> {
        return userDataRepository.isRegister(username)
    }

    //修改密码
    fun updatePassword(userEntity: UserEntity): Flowable<Response> {
        return userDataRepository.updatePassword(userEntity)
    }

    //注册用户信息
    fun registerUser(userEntity: UserEntity): Flowable<Response> {
        return userDataRepository.registerUser(userEntity)
    }

    //获取初始化数据
    fun getIndexData(): Flowable<IndexDataResponse> {
        return userDataRepository.getIndexData()
    }

    //登录并且获取初始化数据
    fun login(username: String, password: String): Flowable<TokenResponse> {

        return userDataRepository.getToken(username, password)
                .doOnNext { userDataRepository.saveToken(it.data?.token) }
                .doOnNext { userDataRepository.logIn() }
    }

    //认证监控视频数据
    fun videoAuth(username: String, password: String): Flowable<LoginData> {
        return Flowable.create(FlowableOnSubscribe<LoginData> {
            VMSNetSDK.getInstance().Login("${ApiConstants.HIK_ENDPOINT}:${ApiConstants.HIK_ENDPOINT_PORT}", username, password, App.getMacAddress(), object : OnVMSNetSDKBusiness() {
                override fun onFailure() {
                    it.onError(Throwable("监控视频认证失败!"))
                }

                override fun onSuccess(obj: Any?) {
                    if (obj is LoginData) {
                        it.onNext(obj)
                    } else {
                        it.onError(Throwable("监控视频认证失败!"))
                    }
                }
            })
        }, BackpressureStrategy.BUFFER)
    }

    //登出
    fun logOut(): Flowable<Boolean> {
        return Flowable.create(FlowableOnSubscribe<Boolean> {
            try {
                clearCache()
                userDataRepository.clearLoginData()
                it.onNext(true)
            } catch (e: Exception) {
                e.printStackTrace()
                it.onNext(false)
            }
        }, BackpressureStrategy.BUFFER)
    }

    //清楚缓存
    private fun clearCache() {
        userDataRepository.clearCache()
    }

    //清楚缓存
    fun clearData(requestType: RequestType) {
        userDataRepository.clearData(requestType)
    }

    //获取用户信息
    fun getAuthenticatedUser(): Flowable<UserEntity> = userDataRepository.getUser()

    //是否登录
    fun isUserLoggedIn(): Boolean = userDataRepository.isUserLoggedIn()

    //是否可以发送
    fun isSendVCode(): Boolean = userDataRepository.isSendVCode()

}